package com.sense.kukoo.biz_me.view

import android.graphics.Bitmap
import android.view.KeyEvent
import android.view.View
import android.webkit.WebView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.Gson
import com.sense.feel.common.global.bean.JsEntity
import com.sense.feel.common.global.bean.WebPage
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.biz_me.R
import com.sense.kukoo.biz_me.databinding.LoginActivityWebBinding
import com.sense.kukoo.biz_me.utils.HttpParamUtil
import com.sense.kukoo.biz_me.vm.WebViewModel
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.constant.ConstantConfig
import com.sense.kukoo.common.constant.JsFunctionConstant
import com.sense.kukoo.common.mvvm.view.BaseMvvmActivity
import com.sense.kukoo.lib_logger.LoggerManager
import com.sense.lib.webview.callback.OnUrlListener

/**
 * <br> ClassName:   WebViewActivity.kt
 * <br> Description: 通用WebView界面
 * <br> Author:      lionszhang
 * <br> Date:        2021/11/9
 */
@Route(path = ARouterUrl.ROUTE_LOGIN_MODULE_WEB_ACTIVITY)
class WebViewActivity : BaseMvvmActivity<WebViewModel, LoginActivityWebBinding>() {
    private var mWebInfo: WebPage? = null
    private var TAG = "WebViewActivity"

    override fun getLayoutId(): Int = R.layout.login_activity_web

    override fun getViewModelClass(): Class<WebViewModel> {
        return WebViewModel::class.java
    }


    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.viewModel = mViewModel
        mViewModel.initData()
        if (intent.hasExtra(ConstantConfig.ARG1)) {
            mWebInfo = intent.getParcelableExtra(ConstantConfig.ARG1)
        }
        LoggerManager.e(TAG, "url>>url=${mWebInfo?.url}")
    }


    override fun initView() {
        initWebView()
        loadUrl()

    }

    private fun loadUrl() {
        mWebInfo?.url?.let { mBinding.webView.loadUrl(it) }
    }

    private fun setJsBridgeCallback() {
        mBinding.webView.setJsBridgeCallBack {
            LoggerManager.e(TAG, "JsBridgeCallBack>>data=$it")
            var gson = Gson()
            var jsEntity = gson.fromJson(it, JsEntity::class.java)
            if (JsFunctionConstant.SWITCH_TAB == jsEntity.funName) {
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_MAIN_MODULE_MAIN_ACTIVITY)
                    .navigation()
                finish()
            } else if (JsFunctionConstant.GO_BACK == jsEntity.funName) {
                goBack()
            } else if (jsEntity.funName == JsFunctionConstant.CLIENT_COMMPARAMS) {
                var jsFunction =
                    String.format("getCommparams('%s');", HttpParamUtil.getCommonParam())
                webViewLoadLocalJs(mBinding.webView, jsFunction)

            }
        }
    }

    private fun webViewLoadLocalJs(view: WebView, path: String?) {
        view.loadUrl("javascript:$path")
    }

    private fun initWebView() {
        setJsBridgeCallback()
        mBinding.webView.setOnUrlListener(object : OnUrlListener {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                LoggerManager.e(TAG, "onPageStarted>>url=${url}")
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                LoggerManager.e(TAG, "onPageFinished>>url=${url}")
                var jsFunction =
                    String.format("getCommparams('%s');", HttpParamUtil.getCommonParam())
                webViewLoadLocalJs(mBinding.webView, jsFunction)
                mBinding.webView.visibility = View.VISIBLE
            }

            override fun onReceivedError(
                view: WebView?,
                errorCode: Int,
                description: String?,
                failingUrl: String?
            ) {
                LoggerManager.e(TAG, "errorCode=${errorCode}, description=${description}, failingUrl=${failingUrl}")
            }

        })
    }

    override fun onResume() {
        super.onResume()
        mBinding.webView.onResume()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goBack()
            return true
        }
        return false
    }

    private fun goBack() {
        when {
            mBinding.webView.canGoBack() -> {
                mBinding.webView.goBack()
            }
            else -> {
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding.webView.clearHistory()
        mBinding.webView.loadUrl("about:blank")
        mBinding.webView.clearCache(true)

    }

    override fun responseVM(action: Int) {
        when (action) {

        }
    }

}